import express from 'express'
import Message from '../models/message'
import Friend from '../models/friend'
import Socket from '../models/socket'
import User from '../models/user'
import {auth} from '../middleware'

const router = express.Router();

//获取好友列表
router.get('/getFriendList', async function (req, res, next) {
  const selfId = req.query.selfId;

  if(!selfId){
    res.json({
      errno: 1,
      msg: '用户 ID 不能为空'
    });
    return;
  }

  const friend = await Friend.find({selfId}).populate({
    path: 'friendId',
    select: 'username nickname avatar address letter'
  });

  res.json({
    errno: 0,
    data: friend,
    msg: '获取成功'
  });
})

//搜索好友
router.post('/searchFriend', auth, async function (req, res, next) {

  const {friendName} = req.body;


  if (friendName === '') {
    res.json({
      errno: 1,
      msg: '用户名不能为空'
    });
    return;
  }

  const userRes = await User.findOne({username: friendName});

  if(userRes){
    res.json({
      errno: 0,
      data: {
        username: userRes.username,
        nickname: userRes.nickname,
        sex: userRes.sex,
        avatar: userRes.avatar,
        address: userRes.address,
        sign: userRes.sign,
        id: userRes.id
      },
      msg: '搜索成功'
    })
  }else{
    res.json({
      errno: 1,
      msg: '用户不存在'
    });
  }

})

//添加好友
router.post('/addFriend', auth, async function (req, res, next) {

  const {selfId, friendId} = req.body;

  if (selfId === friendId) {
    res.json({
      errno: 1,
      msg: '不能添加自己为好友'
    })
    return;
  }

  const checkFriend = await Friend.find({selfId, friendId});

  if (checkFriend.length !== 0) {
    res.json({
      errno: 1,
      msg: '您已经添加过该好友，请勿重复添加'
    });
    return;
  }

  const friendMoal = {
    selfId,
    friendId,
  }

  const friendReverseMoal = {
    selfId: friendId,
    friendId: selfId,
  }


  await new Friend(friendMoal).save();

  await new Friend(friendReverseMoal).save();

  try{
    const selfSocket = await Socket.findOne({userId: selfId});

    global.io.to(selfSocket.socketId).emit('addFriend');

    const friendSocket = await Socket.findOne({userId: friendId});

    global.io.to(friendSocket.socketId).emit('addFriend');

  }catch (e) {
    global.logger.error(e);
  }

  res.json({
    msg: '添加成功',
    errno: 0,
  });

})

router.post('/deleteFriend', auth, async function (req, res, next) {
  const {selfId, friendId} = req.body;

  await Friend.deleteOne({selfId, friendId})
  await Friend.deleteOne({friendId, selfId})

  try{
    const selfSocket = await Socket.findOne({userId: selfId});

    global.io.to(selfSocket.socketId).emit('addFriend');

    const friendSocket = await Socket.findOne({userId: friendId});

    global.io.to(friendSocket.socketId).emit('addFriend');

  }catch (e) {
    global.logger.error(e);
  }finally {
    res.json({
      msg: '删除成功',
      errno: 0,
    });
  }

})

export default router
